<template>
  <div class="container">
    <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" size="50" />

    <template v-else>
      <van-nav-bar
        left-arrow
        :fixed="true"
        z-index="10"
        title="城市选择"
        @click-left="onClickLeft"
      />

      <van-index-bar :index-list="indexList" sticky :sticky-offset-top="navBarHeight">
        <template v-for="letter in indexList" :key="letter">
          <!-- 中文汉字索引部分 -->

          <!-- 定位城市 -->
          <template v-if="charsIndexList[0] === letter">
            <div class="location">
              <van-index-anchor :index="letter" class="no-padding">
                <template #default>
                  <!-- <div class="title">定位城市</div> -->
                  定位城市
                </template>
              </van-index-anchor>

              <div class="list">
                <van-button
                  plain
                  hairline
                  class="location-city-btn"
                  :data-id-cityId="locationCity.cityId"
                  @click="clickCity(locationCity)"
                  :class="locationCity.cityId === currentCity.cityId ? 'active_city' : ''"
                  >{{ locationCity.cityName }}</van-button
                >
              </div>
            </div>
          </template>

          <!-- 最近访问城市 -->
          <template v-if="charsIndexList[1] === letter">
            <div class="history">
              <van-index-anchor :index="letter" class="no-padding">
                <template #default>
                  <div class="title">最近访问城市</div>
                </template>
              </van-index-anchor>
              <div class="list">
                <van-button
                  plain
                  hairline
                  class="history-city-btn"
                  v-for="recentCity in recentCities"
                  @click="clickCity(recentCity)"
                  :key="recentCity.cityId"
                  :data-id-cityId="recentCity.cityId"
                  :class="recentCity.cityId === currentCity.cityId ? 'active_city' : ''"
                  >{{ recentCity.cityName }}</van-button
                >
              </div>
            </div>
          </template>

          <!-- 热门城市 -->
          <template v-if="charsIndexList[2] === letter">
            <div class="hot">
              <van-index-anchor :index="letter" class="no-padding">
                <template #default>
                  <div class="title">热门城市</div>
                </template>
              </van-index-anchor>

              <div class="list">
                <van-button
                  plain
                  hairline
                  :data-id-cityId="hotCity.cityId"
                  class="hot-city-btn"
                  v-for="hotCity in cityList.hotCities"
                  @click="clickCity(hotCity)"
                  :key="hotCity.cityId"
                  :class="hotCity.cityId === currentCity.cityId ? 'active_city' : ''"
                  >{{ hotCity.cityName }}</van-button
                >
              </div>
            </div>
          </template>

          <!-- 英文字母索引部分 -->
          <template v-if="letterIndexList.includes(letter)">
            <van-index-anchor :index="letter" />
            <template v-for="(title_cities, groupIndex) in cityList.allCities" :key="groupIndex">
              <!-- <template v-for="city in title_cities.cities" :key="title_cities.title"> -->
              <template v-for="city in title_cities.cities" :key="city.cityOID">
                <van-cell
                  :title="city.cityName"
                  :data-id-cityId="city.cityOID"
                  v-if="title_cities.title === letter"
                  @click="clickCity({ cityName: city.cityName, cityId: city.cityOID })"
                />
              </template>
            </template>
          </template>
        </template>
      </van-index-bar>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { fetchCityList } from '@/api/index.js'
import { useStore } from '@/stores/index'
const store = useStore() //store 实例
import { useRouter } from 'vue-router'
const router = useRouter()

/*  变量  */
//页面loading
const loading = ref(true)

//A-Z索引
const letterIndexList = ref(
  Array.from(
    { length: 26 },
    (_, i) => String.fromCharCode(65 + i), // 生成 A-Z 数组
  ),
)
// 中文索引
const charsIndexList = ref(['定位', '历史', '热门'])
// 综合索引
const indexList = computed(() => [...charsIndexList.value, ...letterIndexList.value])

/* 计算属性 */
// 添加导航栏高度计算
const navBarHeight = computed(() => {
  // 获取 CSS 变量值，如果获取不到则使用默认值 46
  const rootStyle = getComputedStyle(document.documentElement)
  const navBarHeight = rootStyle.getPropertyValue('--van-nav-bar-height')
  return navBarHeight ? parseInt(navBarHeight) : 46
})

//定位城市
const locationCity = computed(() => {
  return store.locationCity
})

//当前城市
const currentCity = computed(() => {
  return store.currentCity
})
// 历史访问城市
const recentCities = computed(() => {
  return store.cityList.historyCities
})

//城市列表
const cityList = reactive({
  allCities: [],
  hotCities: [],
  historyCities: [],
})

/*  生命周期  */
onMounted(async () => {
  loading.value = true
  // 加载城市列表
  //如果store没有有数据,则进行请求
  if (store.cityList.allCities.length === 0 && store.cityList.hotCities.length === 0) {
    await loadCityList()
  } else {
    //如果store有数据,则直接使用
    cityList.allCities = store.cityList.allCities
    cityList.hotCities = store.cityList.hotCities
  }
  loading.value = false
  // console.log('全部城市:', cityList.allCities)
})

/* 方法 */

//加载城市列表
const loadCityList = async () => {
  const res = await fetchCityList()
  // console.log(res)
  if (res.statusCode == 200) {
    cityList.allCities = res.result?.allCities

    const hots = res.result?.hotCities.map((city) => {
      return { cityId: city.cityOID, cityName: city.cityName }
    })

    cityList.hotCities = hots

    // 城市列表数据同步保存到store
    store.setCityList(cityList.allCities, cityList.hotCities)
  }
}

// 点击城市
// 1.保存点击城市为历史城市
// 2.设定当前访问的城市
// 3.返回首页
const clickCity = (city) => {
  store.unshiftHistoryCities(city)

  store.setCurrentCity(city.cityName, city.cityId)

  // 添加查询参数标识来源页面
  router.push('/?from=CityList')
}

// 返回前一页
const onClickLeft = () => {
  router.back(-1)
}
</script>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  background-color: #f2f2f2;
  padding-top: var(--van-nav-bar-height); // 使用 Vant 的导航栏高度变量

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  :deep(.van-index-bar__index) {
    height: 20px;
  }

  .location {
    .no-padding {
      height: auto;
    }

    .title {
      background-color: #f2f2f2;
    }

    .list {
      padding-left: 16px;
      margin-top: 10px;

      .location-city-btn {
        border-radius: 4px;
        font-size: 18px;
        width: 100px;
      }
    }
  }

  .history {
    .no-padding {
      height: auto;
    }

    .title {
      background-color: #f2f2f2;
    }

    .list {
      padding-left: 16px;
      margin-top: 10px;

      .history-city-btn {
        border-radius: 4px;
        font-size: 18px;
        width: 100px;
      }
    }
  }

  .hot {
    .no-padding {
      height: auto;
    }

    .title {
      background-color: #f2f2f2;
    }

    .list {
      margin-top: 10px;
      padding-left: 16px;
      display: flex;
      gap: 20px;
      flex-wrap: wrap;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      align-content: center;

      .hot-city-btn {
        border-radius: 4px;
        font-size: 18px;
        width: 100px;
      }
    }
  }
}

:deep(.van-index-anchor) {
  font-size: 16px;
  color: #aaa;
  padding-top: 10px;
}

:deep(.van-index-anchor--sticky) {
  background-color: #f2f2f2;
}

:deep(.van-cell__title) {
  font-size: 18px;
}

.active_city {
  border-color: #fd6857;
  color: #fd6857;
}
</style>
